import jwt
import time

from flask import current_app, g, request
from app.models.Auth import Auth
from app.models.Student import Student


def generate_jwt(auth_id):
    token_dict = {
        'iat': time.time() + 60 * 60 * 24,
        'auth_id': auth_id
    }
    return jwt.encode(token_dict,
                      current_app.config['JWT_SECRET'],
                      algorithm='HS256',
                      )


def verify_jwt(token):
    try:
        payload = jwt.decode(token, current_app.config['JWT_SECRET'], algorithms='HS256')
        if payload['iat'] < time.time():
            return False, "登入超时", 504
        auth_id = payload['auth_id']
        auth = Auth.get_by_auth_id(auth_id)
        if auth is None:
            return False, "无此用户", 404
        return True, auth, 200
    except:
        return False, "数据错误", 404


def auth_check(authorization):
    if authorization:
        typ, token = authorization.split()
        if typ == 'Bearer':
            g.token = token
            success, auth, code = verify_jwt(token)
            if not success:
                g.auth_id = None
            else:
                if auth['priority'] == 0:
                    g.priority = 0
                    g.auth_id = auth['auth_id']
                elif auth['priority'] == 1:
                    g.priority = 1
                    g.auth_id = auth['auth_id']
                else:
                    g.auth_id = None
        else:
            g.auth_id = None
    else:
        g.auth_id = None
